package com.wonders.frame.service;

import com.wonders.frame.common.Enum.CommonSourceKeyEnum;
import com.wonders.frame.common.Enum.InitCommonSourceEnum;
import com.wonders.frame.common.Enum.RemovedCodeEnum;
import com.wonders.frame.common.Utils;
import com.wonders.frame.common.util.Md5Util;
import com.wonders.frame.entity.AuthAccount;
import com.wonders.frame.entity.AuthAccountRole;
import com.wonders.frame.entity.AuthOrga;
import com.wonders.frame.entity.AuthUser;
import com.wonders.frame.entity.form.AuthUserForm;
import com.wonders.frame.repository.AuthAccountRepository;
import com.wonders.frame.repository.AuthAccountRoleRepository;
import com.wonders.frame.repository.AuthOrgaRepository;
import com.wonders.frame.repository.AuthUserRepository;
import com.wonders.frame.repository.core.CoreRepository;
import com.wonders.frame.service.Core.CoreCurdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AuthUserService extends CoreCurdService<AuthUser> {
    Logger log = LoggerFactory.getLogger(AuthUserService.class);

    public static final String FLYER_ROLE="2c9280836ab5f055016ab634b31117dd";
    public static final String TEAMLEADER_ROLE="407e851e6a100061016a100298920001";

    @Autowired
    private AuthUserRepository authUserRepository;
    @Override
    protected CoreRepository<AuthUser> getRepository() {
        return authUserRepository;
    }

    @Autowired
    private AuthOrgaRepository authOrgaRepository;
    @Autowired
    private AuthAccountRepository authAccountRepository;

    @Autowired
    private AuthAccountRoleRepository authAccountRoleRepository;


    //判断唯一性 账号
    public boolean checkUniqueAccount(AuthUserForm authUserForm){
        //修改
        if(!StringUtils.isEmpty(authUserForm.getId())){
            AuthUser authUser=new AuthUser();
            authUser.setId(authUserForm.getId());
            //判断是否修改了账号
            AuthAccount authAccount =authAccountRepository.findByUserAndRemoved(authUser, RemovedCodeEnum.AVAILABLE.getCode());
            if(authUserForm.getAccount().equals(authAccount.getAccount())){
                return true;
            }
        }

        //根据账号查询修改后的账号是否存在
        List<AuthAccount> list =authAccountRepository.findByAccountAndRemoved(authUserForm.getAccount(),RemovedCodeEnum.AVAILABLE.getCode());
        if(CollectionUtils.isEmpty(list)){
            return true;
        }
        return false;
    }

    //判断唯一性  证件编号
    public boolean checkUniqueCertnum(AuthUserForm authUserForm){
        //修改
        if(!StringUtils.isEmpty(authUserForm.getId())){
            AuthUser authUser=authUserRepository.findByIdAndRemoved(authUserForm.getId(),RemovedCodeEnum.AVAILABLE.getCode());
            //没修改证件编号
            if(authUserForm.getCertnum().equals(authUser.getCertnum())){
                return true;
            }
        }

        //根据账号查询修改后的账号是否存在
        List<AuthUser> list =authUserRepository.findByCertnumAndRemoved(authUserForm.getCertnum(),RemovedCodeEnum.AVAILABLE.getCode());
        if(CollectionUtils.isEmpty(list)){
            return true;
        }
        return false;
    }

    @Transactional
    public AuthUser save(AuthUserForm authUserForm,AuthAccount loginAccount){
        //先新增auth_user
        AuthUser authUser=new AuthUser();
        BeanUtils.copyProperties(authUserForm,authUser);
        if(StringUtils.isEmpty(authUserForm.getId())){
            log.debug("new user");
            authUser.setCrtDate(new Date());
            authUser.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
        }else{
            //修改时  创建人和创建时间不改
            AuthUser authUser1=authUserRepository.getOne(authUserForm.getId());
            authUser.setCrtDate(authUser1.getCrtDate());
            authUser.setCrtUser(authUser1.getCrtUser());
        }

        //拼接飞防组织名称
        String orgaId=getOrgaId(authUserForm.getDeptId());
        String deptId=authUserForm.getDeptId();
        AuthOrga orga=authOrgaRepository.getOne(deptId);
        if(deptId.equals(orgaId)){
            authUser.setOrgaName(orga.getOrgaName());
        }else{
            AuthOrga orga1=authOrgaRepository.getOne(orgaId);
            authUser.setOrgaName(orga1.getOrgaName()+"("+orga.getOrgaName()+")");
        }


        //状态设置为正常
        authUser.setStatus("1");
        //把账号设置成手机号
        authUser.setPhone(authUserForm.getAccount());
        authUser.setUpdDate(new Date());
        authUser=authUserRepository.save(authUser);


        //新增时  把新增的用户加到当前登录人的成员收藏


        //新增auth_account  不能修改
        AuthAccount authAccount=new AuthAccount();
        //新增
        if(StringUtils.isEmpty(authUserForm.getId())){
            authAccount.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
            authAccount.setAccount(authUserForm.getAccount());
            authAccount.setPassword(Md5Util.getMd5(authUserForm.getAccount() + authUserForm.getPassword()));
            authAccount.setCrtDate(new Date());
            authAccount.setType("fs");
        }else{
            //查询之前的值
            authAccount=authAccountRepository.getOne(authUserForm.getAccountId());
        }
        authAccount.setOrgaId(orgaId);
        authAccount.setDeptId(deptId);
        authAccount.setUpdDate(new Date());
        authAccount.setUser(authUser);

        authAccount=authAccountRepository.save(authAccount);

        //先删除队长和飞手角色
        authAccountRoleRepository.deleteByAccountIdAndRoleId(authUserForm.getAccountId(),FLYER_ROLE);
        authAccountRoleRepository.deleteByAccountIdAndRoleId(authUserForm.getAccountId(),TEAMLEADER_ROLE);

        AuthAccountRole authAccountRole=new AuthAccountRole();
        if("fs".equals(authUserForm.getPosition())){
            authAccountRole.setRoleId(FLYER_ROLE);
        }
        if("dz".equals(authUserForm.getPosition())){
            authAccountRole.setRoleId(TEAMLEADER_ROLE);
        }
        authAccountRole.setAccountId(authAccount.getId());
        authAccountRole.setRemoved(RemovedCodeEnum.AVAILABLE.getCode());
        authAccountRoleRepository.save(authAccountRole);

        return authUser;
    }


    //判断是否是自己的账号
    public boolean isSelf(String userId,String account){
        AuthUser authUser=authUserRepository.findByIdAndRemoved(userId,RemovedCodeEnum.AVAILABLE.getCode());
        AuthAccount authAccount=authAccountRepository.findByUserAndRemoved(authUser,RemovedCodeEnum.AVAILABLE.getCode());
        //自己不能转出转入自己的账号
        if(authAccount.getAccount().equals(account)){
            return true;
        }
        return false;
    }

    //注销 删除 removed改成删除 auth_user的status改成注销
    @Transactional
    public void deleteById(String userId){
        //逻辑删除auth_user 和auth_account
        AuthUser authUser=authUserRepository.findByIdAndRemoved(userId,RemovedCodeEnum.AVAILABLE.getCode());
        authUser.setRemoved(RemovedCodeEnum.REMOVED.getCode());
        //设置状态为注销
        authUser.setStatus("3");

        AuthAccount authAccount=authAccountRepository.findByUserAndRemoved(authUser,RemovedCodeEnum.AVAILABLE.getCode());
        authAccount.setRemoved(RemovedCodeEnum.REMOVED.getCode());
        authAccountRepository.save(authAccount);
        authUserRepository.save(authUser);
    }

    /**
     * 转出
     * 修改auth_user的status为转出
     * 修改auth_account的orga_id为null
     * @param userId
     */
    @Transactional
    public void changeStatusOut(String userId){
        AuthUser authUser=authUserRepository.findByIdAndRemoved(userId,RemovedCodeEnum.AVAILABLE.getCode());
        //状态改成转出
        authUser.setStatus("2");
        authUser.setOrgaName(null);
        authUserRepository.save(authUser);

        AuthAccount authAccount=authAccountRepository.findByUserAndRemoved(authUser,RemovedCodeEnum.AVAILABLE.getCode());
        //转出组织
        authAccount.setOrgaId(Utils.ZYFS);
        authAccount.setDeptId(Utils.ZYFS);
        authAccountRepository.save(authAccount);
    }

    /**
     * 转入
     * 修改auth_user的status为正常
     * 修改auth_account的orga_id为当期用户的orga_id
     * @param orgaId
     * @param userId
     */
    @Transactional
    public void changeStatusIn(String orgaId,String deptId,String userId){
        AuthUser authUser=authUserRepository.findByIdAndRemoved(userId,RemovedCodeEnum.AVAILABLE.getCode());


        AuthOrga orga=authOrgaRepository.getOne(deptId);
        if(deptId.equals(orgaId)){
            authUser.setOrgaName(orga.getOrgaName());
        }else{
            AuthOrga orga1=authOrgaRepository.getOne(orgaId);
            authUser.setOrgaName(orga1.getOrgaName()+"("+orga.getOrgaName()+")");
        }

        //状态改成正常
        authUser.setStatus("1");
        authUserRepository.save(authUser);

        AuthAccount authAccount=authAccountRepository.findByUserAndRemoved(authUser,RemovedCodeEnum.AVAILABLE.getCode());

        authAccount.setOrgaId(orgaId);
        authAccount.setDeptId(deptId);
        authAccountRepository.save(authAccount);
    }

    /**
     * 根据deptId 判断当前机构是部门还是机构
     * 如果是机构 返回当前值即可
     * 如果是部门 回溯父节点 判断是机构还是部门
     * 如果是机构 返回父节点orgaId 如果是部门 继续查父节点
     * @param deptId
     * @return
     */
    public static String getOrgaId(String deptId){
        Map<String, Object> map= InitCommonSourceEnum.getCommonSource(CommonSourceKeyEnum.ORGA.name());
        if(!StringUtils.isEmpty(deptId)){
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                AuthOrga authOrga=((AuthOrga) entry.getValue());
                if(deptId.equals(authOrga.getId())&&authOrga.getRemoved()==RemovedCodeEnum.AVAILABLE.getCode()){
                   //判断是机构还是部门  1是机构 2是部门
                   if("1".equals(authOrga.getOrgaType())){
                       //return authOrga.getParentId().isEmpty()?deptId:authOrga.getParentId();
                       return deptId;
                   } else if("2".equals(authOrga.getOrgaType())){
                       return getOrgaId(authOrga.getParentId());
                   }
                }
            }
        }
        return null;
    }


}
